package com.hatricks.is.algorithm.threesum;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@SuppressWarnings("DuplicatedCode")
public class ThreeSum {

    public static List<List<Integer>> threeSum(int[] nums, int target) {
        List<List<Integer>> result = new ArrayList<>();
        // 1. 排序
        Arrays.sort(nums);
        // 2. 遍历每个元素，固定当前元素
        for (int i = 0; i < nums.length - 2; i++) {
            // 跳过重复元素，避免重复计算
            //if (i > 0 && nums[i] == nums[i - 1]) continue;
            // 3. 双指针法，寻找另外两个数
            int left = i + 1;
            int right = nums.length - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) {
                    // 找到了一个符合条件的三元组
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    //while (left < right && nums[left] == nums[left + 1]) left++;
                    //while (left < right && nums[right] == nums[right - 1]) right--;
                    // 移动指针
                    left++;
                    right--;
                } else if (sum < target) {
                    // 如果和小于目标值，左指针右移
                    left++;
                } else {
                    // 如果和大于目标值，右指针左移
                    right--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {-3, -2, -1, 0, 1, 2, 3, 4};
        int target = 0;

        List<List<Integer>> result = threeSum1(nums, target);
        // 打印结果
        for (List<Integer> triplet : result) {
            System.out.println(triplet);
        }
    }

    public static List<List<Integer>> threeSum1(int[] nums, int target) {
        List<List<Integer>> result = new LinkedList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == target) {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return result;
    }

}
